package com.example.exchangeapp.yy.request;

import android.os.NetworkOnMainThreadException;
import android.os.ParcelUuid;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.exchangeapp.yy.constant.AppId;
import com.example.exchangeapp.yy.constant.AppSecret;
import com.example.exchangeapp.yy.entity.GoodVo2;
import com.example.exchangeapp.yy.entity.Goods;
import com.example.exchangeapp.yy.entity.GoodsType;
import com.example.exchangeapp.yy.entity.GoodsVo;
import com.example.exchangeapp.yy.entity.GoogSendVo;
import com.example.exchangeapp.yy.entity.GoogsVo3;
import com.example.exchangeapp.yy.entity.Image;
import com.example.exchangeapp.yy.fragment.DialogAddGoods;
import com.example.exchangeapp.yy.fragment.HasSendGoods;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpRequestUtils {
    private static final Gson gson = new Gson();

    //获取所有的商品分类和对于的id

    public static void get(){
        new Thread(() -> {
            // url路径
            String url = "http://47.107.52.7:88/member/tran/goods/type";
            // 请求头
            Headers headers = new Headers.Builder()
                    .add("Accept", "application/json,text/plain, */*")
                    .add("appId", AppId.AppId)
                    .add("appSecret", AppSecret.appSecret)
                    .build();

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .get()
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback1);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }
    /**
     * 回调
     */
    private static final Callback callback1 = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            Type jsonType = new TypeToken<ResponseBody<List<GoodsType>>>(){}.getType();
            // 获取响应体的json串
            String body = response.body().string();
            // 解析json串到自己封装的状态
            ResponseBody<List<GoodsType>> dataResponseBody = gson.fromJson(body,jsonType);
             for (GoodsType goodsType: dataResponseBody.getData()){
                 DialogAddGoods.type_id_maps.put(goodsType.getType(), goodsType.getId());
             }
        }
    };


    //上传图片
    public static void postImage(File file){
        new Thread(() -> {

            // url路径
            String url = "http://47.107.52.7:88/member/tran/image/upload";

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", AppId.AppId)
                    .add("appSecret", AppSecret.appSecret)
                    .add("Accept", "application/json, text/plain, */*")
                    .build();


            MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
            MediaType MEDIA_TYPE_PNG = MediaType.parse("image/*");

            MultipartBody multipartBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    // 这里设置要传给后台的参数；如果要添加多个参数，可以先获取到MultipartBody.Builder对象，然后再for循环添加
                    // 约定key 如 "certificate" 作为后台接受图片的key；这里约定的key是：certificate
                    .addFormDataPart("fileList", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file))
                    .build();

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .post(multipartBody)
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback2);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    /**
     * 回调
     */
    private static final Callback callback2 = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            Type jsonType = new TypeToken<ResponseBody<Image>>(){}.getType();
            // 获取响应体的json串
            String body = response.body().string();

            // 解析json串到自己封装的状态
            ResponseBody<Image> dataResponseBody = gson.fromJson(body,jsonType);

            Image data = dataResponseBody.getData();
            //设置图片的code码
            DialogAddGoods.goods.setImageCode(data.getImageCode());
            HasSendGoods.imageList = data.getImageUrlList();
        }
    };

    public static void postGoos(Goods goods){
        new Thread(() -> {

            // url路径
            String url = "http://47.107.52.7:88/member/tran/goods/add";

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("Accept", "application/json, text/plain, */*")
                    .add("appId", AppId.AppId)
                    .add("appSecret", AppSecret.appSecret)
                    .add("Content-Type", "application/json")
                    .build();

            // 请求体
            // PS.用户也可以选择自定义一个实体类，然后使用类似fastjson的工具获取json串
            Map<String, Object> bodyMap = new HashMap<>();
            bodyMap.put("price",goods.getPrice());
            bodyMap.put("imageCode", goods.getImageCode());
            bodyMap.put("typeName", goods.getTypeName());
            bodyMap.put("typeId", goods.getTypeId());
            bodyMap.put("addr", goods.getAddr());
            bodyMap.put("userId",goods.getUserId());
            bodyMap.put("content", goods.getContent());
            // 将Map转换为字符串类型加入请求体中
            String body = gson.toJson(bodyMap);

            MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .post(RequestBody.create(MEDIA_TYPE_JSON, body))
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback3);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }
    /**
     * 回调
     */
    private  static final Callback callback3 = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            Type jsonType = new TypeToken<ResponseBody<GoodsVo>>(){}.getType();
            // 获取响应体的json串
            String body = response.body().string();

            // 解析json串到自己封装的状态
            ResponseBody<GoodsVo> dataResponseBody = gson.fromJson(body,jsonType);
            String msg = dataResponseBody.getMsg();
            HasSendGoods.index =   dataResponseBody.getData().getId();
            HasSendGoods.msg = msg;
            System.out.println("添加商品返回的数据:"+dataResponseBody);
        }
    };





    public static void getHasSendGoodsNum(String userId,int current,int size){
        new Thread(() -> {
            // url路径
            String url = "http://47.107.52.7:88/member/tran/goods/myself?userId="+userId+"&current="+current+"&size="+size;

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", AppId.AppId)
                    .add("appSecret",AppSecret.appSecret)
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .get()
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback4);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    /**
     * 回调
     */
    private static final Callback callback4 = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            Type jsonType = new TypeToken<ResponseBody<GoogSendVo>>(){}.getType();
            // 获取响应体的json串
            String body = response.body().string();
            // 解析json串到自己封装的状态
            ResponseBody<GoogSendVo> dataResponseBody = gson.fromJson(body,jsonType);

          HasSendGoods.num =dataResponseBody.getData().getTotal();

        }
    };







    public static void getHasSendGoods(String userId,int current,int size){
        new Thread(() -> {
            // url路径
            String url = "http://47.107.52.7:88/member/tran/goods/myself?userId="+userId+"&current="+current+"&"+"size="+size;

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", AppId.AppId)
                    .add("appSecret", AppSecret.appSecret)
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .get()
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback5);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    /**
     * 回调
     */
    private static final Callback callback5 = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            Type jsonType = new TypeToken<ResponseBody<GoogSendVo>>(){}.getType();
            // 获取响应体的json串
            String body = response.body().string();
            // 解析json串到自己封装的状态
            ResponseBody<GoogSendVo> dataResponseBody = gson.fromJson(body,jsonType);
            List<GoodVo2> records = dataResponseBody.getData().records;
            HasSendGoods.data =records;
            HasSendGoods.msg = dataResponseBody.getMsg();
        }
    };

    public   static void getImage(String goodsId){

        new Thread(() -> {

            // url路径
            String url = "http://47.107.52.7:88/member/tran/goods/details?goodsId="+ goodsId;

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", AppId.AppId)
                    .add("appSecret", AppSecret.appSecret)
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .get()
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback6);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    /**
     * 回调
     */
    private static final Callback callback6 = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            Type jsonType = new TypeToken<ResponseBody<GoogsVo3>>(){}.getType();
            // 获取响应体的json串
            String body = response.body().string();

            // 解析json串到自己封装的状态
            ResponseBody<GoogsVo3> dataResponseBody = gson.fromJson(body,jsonType);
            GoogsVo3 data = dataResponseBody.getData();

            if (data!=null&&data.imageUrlList!=null){
                HasSendGoods.imageList =  data.imageUrlList;
            } else HasSendGoods.imageList = new String[]{"https://guet-lab.oss-cn-hangzhou.aliyuncs.com/api/2023/07/30/18b3ccee-d38d-4988-9cbc-49ab43221014.jpg"};

        }
    };


    /**
     * http响应体的封装协议
     * @param <T> 泛型
     */
    public static class ResponseBody <T> {

        /**
         * 业务响应码
         */
        private int code;
        /**
         * 响应提示信息
         */
        private String msg;
        /**
         * 响应数据
         */
        private T data;

        public ResponseBody(){}

        public int getCode() {
            return code;
        }
        public String getMsg() {
            return msg;
        }
        public T getData() {
            return data;
        }

        @NonNull
        @Override
        public String toString() {
            return "ResponseBody{" +
                    "code=" + code +
                    ", msg='" + msg + '\'' +
                    ", data=" + data +
                    '}';
        }
    }




    public static void delete(String uid,String pid){
        new Thread(() -> {

            // url路径
            String url = "http://47.107.52.7:88/member/tran/goods/delete?goodsId="+pid+"&"+"userId="+uid;

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("Accept", "application/json, text/plain, */*")
                    .add("appId", AppId.AppId)
                    .add("appSecret", AppSecret.appSecret)
                    .add("Content-Type", "application/json")
                    .build();
            MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .post(RequestBody.create(MEDIA_TYPE_JSON, ""))
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback8);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    /**
     * 回调
     */
    public static final Callback callback8 = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            Type jsonType = new TypeToken<ResponseBody<ResponseBody>>(){}.getType();
            // 获取响应体的json串
            String body = response.body().string();
            // 解析json串到自己封装的状态
            ResponseBody<ResponseBody> dataResponseBody = gson.fromJson(body,jsonType);
            System.out.println("下架返回的信息:"+dataResponseBody);
           if (dataResponseBody.getCode()==200){
               HasSendGoods.code = 200;
               HasSendGoods.num--;

           }
        }
    };



}
